package com.jams.goodox;


import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.jams.goodox.activity.IBaseActFrag;
import com.jams.goodox.entity.ServerBean;
import com.jams.goodox.listen.DialogActionListener;
import com.jams.goodox.listen.PermissionCallBackListener;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.ProtocolManagers;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.RetrofitHelper;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.CustomPopWindow;
import com.jams.goodox.widget.LoadView;
import com.jams.goodox.widget.LoadingDialog;
import com.jams.goodox.widget.PromptBuilderDialog;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;

public class BaseFragment extends Fragment implements IBaseActFrag {

    public Context mContext;
    public final static int PAGE_SIZE = 20;
    private RetrofitHelper retrofitHelper;
    private LoadingDialog loadingDialog;//加载圈

    protected Map<String,String> params = new HashMap();
    protected Gson gson = new Gson();


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        retrofitHelper = RetrofitHelper.get(mContext);
    }



    protected void clearMap(){
        params.clear();
        //通用参数
        params.put("sign", "test");
        params.put("uuid", "5617222222");
        params.put("accessToken",SePref.getToken());
        params.put("timeStamp",String.valueOf(System.currentTimeMillis()));
        params.put("version",BuildConfig.VERSION_NAME);
    };


    protected PermissionCallBackListener permissionCallBackListener;

    protected <T extends BaseEntity> void  enqueue(Call<T> call, RetrofitCallbackListener<T> callback){
        if(retrofitHelper==null)return;
        retrofitHelper.enqueue(call,callback);
    }

    protected <T> T createCallService(Class<T> apiServiceClass){
        return ProtocolManagers.getInstance().getService(apiServiceClass);
    }

    // //////////////////////////////////////////////////跳转相关/////////////////////////////////////////////////////////////
    @Override
    public void qStartActivity(Intent intent) {
        startActivity(intent);
    }

    @Override
    public void qStartActivity(Class<? extends Activity> cls) {
        qStartActivity(cls, null);
    }

    @Override
    public void qStartActivity(Class<? extends Activity> cls, Bundle bundle) {
        Intent intent = new Intent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        intent.setClass(mActivity, cls);
        startActivity(intent);
    }

    // 服务跳转
    @Override
    public void qStartActivity(ServerBean bean) {

    }

    /**
     * 显示菊花
     */
    protected void showLoading() {
        if(mContext==null||((Activity)mContext).isFinishing())return;
        if (loadingDialog == null) {
            loadingDialog = LoadingDialog.createDialog(mContext);
        }
        loadingDialog.show();
    }

    protected void showLoading(String title) {
        if(mContext==null||((Activity)mContext).isFinishing())return;
        if (loadingDialog == null) {
            loadingDialog = LoadingDialog.createDialog(mContext);
        }
        loadingDialog.setTitile(title);
        loadingDialog.show();

    }

    /**
     * 隐藏菊花
     */
    protected void misLoading() {
        if (loadingDialog != null&&!((Activity)mContext).isFinishing()&&mContext!=null)
            loadingDialog.cancel();
    }

    @Override
    public void qStartActivityForResult(Class<? extends Activity> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        intent.setClass(mActivity, cls);
        startActivityForResult(intent, requestCode);
    }

    /* 带结果返回上一个activity， 配合qStartActivityForResult使用 */
    @Override
    public void qBackForResult(int resultCode, Bundle bundle) {
        Intent intent = new Intent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        mActivity.setResult(resultCode, intent);
        mActivity.finish();
    }

    @Override
    public void qBackToActivity(Class<? extends Activity> cls, Bundle bundle) {
        Intent intent = new Intent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        intent.setClass(mActivity, cls);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

    @Override
    public Context getContext() {
        return mActivity;
    }

    @Override
    public Handler getHandler() {
        return null;
    }

    public Activity mActivity;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;
    }

    public View getLoadMoreBootView(Context c) {
        View view = LayoutInflater.from(c).inflate(R.layout.load_more_footers, null);
        view.setLayoutParams(new DrawerLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        return view;
    }

    //检测相机权限，后期可能添加别的权限
    @TargetApi(Build.VERSION_CODES.M)
    public void checkCameraPermission(PermissionCallBackListener permissionCallBackListener) {
        this.permissionCallBackListener = permissionCallBackListener;
        if (ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            requestPermissions(new String[]{android.Manifest.permission.CAMERA}, 1992);
        } else {
            permissionCallBackListener.success();
        }
    }
    //检测手机读取权限
    @TargetApi(Build.VERSION_CODES.M)
    public void checkReadPhoneStatusPermission(PermissionCallBackListener permissionCallBackListener) {
        this.permissionCallBackListener = permissionCallBackListener;
        if (ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请READ_PHONE_STATE权限
            requestPermissions(new String[]{android.Manifest.permission.READ_PHONE_STATE}, 1992);
        } else {
            permissionCallBackListener.success();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1992) {
            switch (permissions[0]) {
                case android.Manifest.permission.WRITE_EXTERNAL_STORAGE:
                case android.Manifest.permission.READ_EXTERNAL_STORAGE:
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {

                    } else {
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE) ||
                                !ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
                            showSetPermission(R.string.read_file_permission);
                            return;
                        }
                    }
                    break;
                case android.Manifest.permission.CAMERA:
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        permissionCallBackListener.success();
                    } else {
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
                            showSetPermission(R.string.camera_permission_is_need);
                            return;
                        }
                    }
                    break;
                case android.Manifest.permission.READ_PHONE_STATE:
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        permissionCallBackListener.success();
                    } else {
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_PHONE_STATE)) {
                            showSetPermission(R.string.read_status_permission_is_need);
                            return;
                        }
                    }
                    break;
            }
        }
    }

    private void showSetPermission(@StringRes int tip) {
        new PromptBuilderDialog(getActivity())
                .setTitle(R.string.tips)
                .setContent(tip)
                .setPositive(R.string.setting_permission)
                .setNegative(R.string.cancel)
                .setCancelAble(false)
                .setActionClickListener(new DialogActionListener() {
                    @Override
                    public void cancel(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }

                    @Override
                    public void confirm(DialogInterface dialog, int which) {
                        dialog.cancel();
                        //跳转到应用设置页
                        Uri packageURI = Uri.parse("package:" + BuildConfig.APPLICATION_ID);
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        startActivity(intent);
                    }
                })
                .show();

    }

    protected LoadView loadView;

    // 页面数据加载中遮罩层
    public void loading() {
        if (loadView != null) {
            loadView.onLoad();
        }
    }

    // 加载完成时候隐藏遮罩层
    public void loadComplate() {
        if (loadView != null) {
            loadView.onloadFinish();
        }
    }

    // 加载失败时候显示重新加载
    public void loadError() {
        if (loadView != null) {
            loadView.onError();
        }
    }


    // 加载失败时候显示重新加载
    public void loadErrorWithNoToast() {
        if (loadView != null) {
            loadView.onError();
        }
    }


    // 页面数据加载完成时候并且数据为空 显示空数据页面
    public void loadCompleteNoData(int text, int imgResId) {
        if (loadView != null) {
            loadView.onNoDate(text, imgResId);
        }
    }


    // 加载失败时候 点击重新加载
    public void setReloadListener(LoadView.ReloadListener reloadListener) {
        if (loadView != null) {
            loadView.setReloadListener(reloadListener);
        }
    }

    public void showNetErrorToast() {
        ToastUtil.showNetErrorToast();
    }
    public void cancelAllCall(){
        retrofitHelper.cancelCalls();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        retrofitHelper.cancelCalls();
    }
}
